package com.blue.user.mq.beans;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Data
@Component
public class RabbitBeanUtil {

    @Autowired
    private final DefaultListableBeanFactory defaultListableBeanFactory;

    @Autowired
    private final AutowireCapableBeanFactory autowireCapableBeanFactory;

    /**
     * 获取rabbitmq连接工厂
     */
    public CachingConnectionFactory getRabbitConnFactory(Integer envIndex) {
        String env = RabbitConnConfig.ENV.get(envIndex);
        if (StringUtils.isEmpty(env)) {
            throw new RuntimeException("不存在此环境");
        }
        return (CachingConnectionFactory) defaultListableBeanFactory.getBean(env + "ConnectionFactory");
    }

    /**
     * 获取rabbitmq配置Template
     */
    public RabbitTemplate getRabbitTemplate(Integer envIndex) {
        String env = RabbitConnConfig.ENV.get(envIndex);
        if (StringUtils.isEmpty(env)) {
            throw new RuntimeException("不存在此环境");
        }
        return (RabbitTemplate) defaultListableBeanFactory.getBean(env + "RabbitTemplate");
    }

}
